#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent): QMainWindow(parent),ui(new Ui::MainWindow)
{
    qDebug() << "Main Thread : " << QThread::currentThreadId();

    ui->setupUi(this);

    m_pStartButton = new QPushButton("start");
    m_pStopButton = new QPushButton("stop");
    m_pControlHBLayout = new QHBoxLayout;
    m_pControlHBLayout->addWidget(m_pStartButton,0,Qt::AlignCenter);
    m_pControlHBLayout->addWidget(m_pStopButton,1,Qt::AlignCenter);

    m_pProgressBar = new QProgressBar;
    m_pProgressBar->setFixedHeight(25);
    m_pProgressBar->setRange(0, 100);
    m_pProgressBar->setValue(0);


    m_pGlobalVBLayout = new QVBoxLayout;
    m_pGlobalVBLayout->addLayout(m_pControlHBLayout);
    m_pGlobalVBLayout->addWidget(m_pProgressBar);
    m_pGlobalVBLayout->setSpacing(50);
    m_pGlobalVBLayout->setContentsMargins(10, 10, 10, 10);

    ui->centralWidget->setLayout(m_pGlobalVBLayout);
    setFixedSize(400,400);

    m_pWorkerThread = new WorkerThread(this);

    connect(m_pStartButton, SIGNAL(clicked(bool)), this, SLOT(startThread()));
    connect(m_pStopButton, SIGNAL(clicked(bool)), this, SLOT(stopThread()));

    // worker thread周期性的更新进度条
    connect(m_pWorkerThread, SIGNAL(resultReady(int)), this, SLOT(handleResults(int)));
    // 线程结束后，自动销毁，如果注释掉下面这行代码，则重新按开始键可以新开一个线程，从0继续刷新进度条
    //connect(m_pWorkerThread, SIGNAL(finished()), m_pWorkerThread, SLOT(deleteLater()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleResults(int value)
{
    qDebug() << "Handle Thread : " << QThread::currentThreadId();
    m_pProgressBar->setValue(value);
}

// 开启线程
void MainWindow::startThread()
{
    if (!m_pWorkerThread->isRunning()){
        qDebug() << " m_workerThread is stoped run it";
        m_pWorkerThread->start();
    }
}

// 停止线程
void MainWindow::stopThread()
{
    //执行WorkerThread类的stop函数，设置需要停止标志位m_bNeedStopped为true，让线程退出主循环
    m_pWorkerThread->stop();
}






